<!-- 背景设置组件 -->
<template>
  <el-drawer
    v-model="visible"
    title="背景设置"
    direction="rtl"
    size="350px"
    :with-header="true"
    :destroy-on-close="false"
    :modal="true"
    :show-close="true"
    :close-on-click-modal="true"
    :close-on-press-escape="true"
  >
    <div class="background-settings-content">
      <!-- 背景类型选择 -->
      <div class="setting-group">
        <div class="setting-label">背景类型</div>
        <el-radio-group v-model="backgroundType" size="small">
          <el-radio-button label="solid">纯色</el-radio-button>
          <el-radio-button label="gradient">渐变</el-radio-button>
          <el-radio-button label="image">图片</el-radio-button>
        </el-radio-group>
      </div>
      
      <!-- 纯色背景设置 -->
      <div class="setting-group" v-if="backgroundType === 'solid'">
        <div class="setting-label">背景颜色</div>
        <el-color-picker v-model="backgroundColor" show-alpha></el-color-picker>
      </div>
      
      <!-- 渐变背景设置 -->
      <div v-if="backgroundType === 'gradient'">
        <div class="setting-group">
          <div class="setting-label">渐变类型</div>
          <el-radio-group v-model="gradientType" size="small">
            <el-radio-button label="linear">线性渐变</el-radio-button>
            <el-radio-button label="radial">径向渐变</el-radio-button>
          </el-radio-group>
        </div>
        
        <!-- 线性渐变设置 -->
        <div v-if="gradientType === 'linear'" class="setting-group">
          <div class="setting-label">渐变方向</div>
          <el-select v-model="gradientDirection" size="small">
            <el-option label="从上到下" value="to bottom"></el-option>
            <el-option label="从左到右" value="to right"></el-option>
            <el-option label="从左上到右下" value="to bottom right"></el-option>
            <el-option label="从右上到左下" value="to bottom left"></el-option>
          </el-select>
        </div>
        
        <!-- 径向渐变设置 -->
        <div v-if="gradientType === 'radial'" class="setting-group">
          <div class="setting-label">渐变形状</div>
          <el-select v-model="radialShape" size="small">
            <el-option label="圆形" value="circle"></el-option>
            <el-option label="椭圆形" value="ellipse"></el-option>
          </el-select>
          
          <div class="setting-label mt-2">渐变位置</div>
          <el-select v-model="radialPosition" size="small">
            <el-option label="中心" value="center"></el-option>
            <el-option label="左上" value="top left"></el-option>
            <el-option label="右上" value="top right"></el-option>
            <el-option label="左下" value="bottom left"></el-option>
            <el-option label="右下" value="bottom right"></el-option>
          </el-select>
        </div>
        
        <div class="setting-group">
          <div class="setting-label">起始颜色</div>
          <el-color-picker v-model="gradientColorStart" show-alpha></el-color-picker>
          
          <div class="setting-label mt-2">结束颜色</div>
          <el-color-picker v-model="gradientColorEnd" show-alpha></el-color-picker>
        </div>
      </div>
      
      <!-- 图片背景设置 -->
      <div v-if="backgroundType === 'image'">
        <div class="setting-group">
          <div class="setting-label">背景图片URL</div>
          <el-input 
            v-model="backgroundImage" 
            placeholder="输入图片URL或选择本地图片" 
            size="small"
          ></el-input>
          
          <div class="mt-2">
            <el-upload
              action=""
              :auto-upload="false"
              :show-file-list="false"
              :on-change="handleFileChange"
              accept="image/*"
            >
              <el-button size="small" type="primary">选择本地图片</el-button>
            </el-upload>
          </div>
        </div>
        
        <div class="setting-group">
          <div class="setting-label">预设图片</div>
          <div class="preset-images">
            <div 
              v-for="(image, index) in presetImages" 
              :key="index" 
              class="preset-image" 
              :style="{ backgroundImage: `url(${image})` }"
              @click="backgroundImage = image"
            ></div>
          </div>
        </div>
      </div>
      
      <!-- 透明度设置 -->
      <div class="setting-group">
        <div class="setting-label">背景透明度</div>
        <el-slider v-model="opacity" :min="0" :max="1" :step="0.01"></el-slider>
      </div>
      
      <!-- 操作按钮 -->
      <div class="setting-actions">
        <el-button type="primary" @click="saveSettings">保存设置</el-button>
        <el-button @click="resetSettings">重置默认</el-button>
      </div>
    </div>
  </el-drawer>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import axios from '../../utils/axios'

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['update:modelValue', 'settings-updated'])

// 控制抽屉显示
const visible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

// 环境变量
const isDevelopment = computed(() => process.env.NODE_ENV === 'development')

// 背景设置状态
const backgroundType = ref('gradient')
const backgroundColor = ref('rgba(107, 70, 193, 0.8)')
const gradientType = ref('linear')
const gradientDirection = ref('to bottom right')
const gradientColorStart = ref('rgba(107, 70, 193, 0.8)')
const gradientColorEnd = ref('rgba(72, 41, 178, 0.8)')
const backgroundImage = ref('')
const opacity = ref(0.9)
const radialShape = ref('circle')
const radialPosition = ref('center')

// 预设图片
const presetImages = [
  '/backgrounds/ganyu.png',
  'https://images.unsplash.com/photo-1557682250-33bd709cbe85?q=80',
  'https://images.unsplash.com/photo-1579546929518-9e396f3cc809?q=80',
  'https://images.unsplash.com/photo-1550684376-efcbd6e3f031?q=80',
  'https://images.unsplash.com/photo-1518655048521-f130df041f66?q=80'
]

// 监听抽屉打开，加载设置
watch(() => visible.value, (newValue) => {
  if (newValue) {
    loadSettings()
  }
})

// 从数据库或本地存储加载设置
const loadSettings = async () => {
  try {
    // 尝试从API加载
    try {
      console.log('尝试从API加载背景设置')
      const response = await axios.get('/api/settings/background/')
      if (response.data) {
        const settings = response.data
        backgroundType.value = settings.backgroundType || 'gradient'
        backgroundColor.value = settings.backgroundColor || 'rgba(107, 70, 193, 0.8)'
        gradientType.value = settings.gradientType || 'linear'
        gradientDirection.value = settings.gradientDirection || 'to bottom right'
        gradientColorStart.value = settings.gradientColorStart || 'rgba(107, 70, 193, 0.8)'
        gradientColorEnd.value = settings.gradientColorEnd || 'rgba(72, 41, 178, 0.8)'
        backgroundImage.value = settings.backgroundImage || ''
        opacity.value = settings.opacity !== undefined ? settings.opacity : 0.9
        radialShape.value = settings.radialShape || 'circle'
        radialPosition.value = settings.radialPosition || 'center'
      }
    } catch (apiError) {
      // API不存在，使用本地存储，不输出警告
      console.log('使用本地存储加载背景设置')
      // 尝试从localStorage加载
      const savedSettings = localStorage.getItem('background_settings')
      if (savedSettings) {
        try {
          console.log('从本地存储加载背景设置')
          const settings = JSON.parse(savedSettings)
          backgroundType.value = settings.backgroundType || 'gradient'
          backgroundColor.value = settings.backgroundColor || 'rgba(107, 70, 193, 0.8)'
          gradientType.value = settings.gradientType || 'linear'
          gradientDirection.value = settings.gradientDirection || 'to bottom right'
          gradientColorStart.value = settings.gradientColorStart || 'rgba(107, 70, 193, 0.8)'
          gradientColorEnd.value = settings.gradientColorEnd || 'rgba(72, 41, 178, 0.8)'
          backgroundImage.value = settings.backgroundImage || ''
          opacity.value = settings.opacity !== undefined ? settings.opacity : 0.9
          radialShape.value = settings.radialShape || 'circle'
          radialPosition.value = settings.radialPosition || 'center'
        } catch (parseError) {
          console.error('解析本地存储的背景设置失败，使用默认设置', parseError)
          resetSettings()
        }
      } else {
        // 没有本地存储，使用默认设置
        console.log('没有找到本地存储的背景设置，使用默认设置')
        resetSettings()
      }
    }
  } catch (error) {
    console.error('加载背景设置失败，使用默认设置', error)
    resetSettings()
  }
}

// 保存设置
const saveSettings = async () => {
  const settings = {
    backgroundType: backgroundType.value,
    backgroundColor: backgroundColor.value,
    gradientType: gradientType.value,
    gradientDirection: gradientDirection.value,
    gradientColorStart: gradientColorStart.value,
    gradientColorEnd: gradientColorEnd.value,
    backgroundImage: backgroundImage.value,
    opacity: opacity.value,
    radialShape: radialShape.value,
    radialPosition: radialPosition.value
  }
  
  try {
    // 尝试保存到API
    try {
      console.log('尝试保存背景设置到API')
      await axios.post('/api/settings/background/', settings)
      ElMessage.success('背景设置已保存到服务器')
    } catch (apiError) {
      // API不存在，保存到本地存储
      console.log('保存背景设置到本地存储')
      localStorage.setItem('background_settings', JSON.stringify(settings))
      ElMessage.success('背景设置已保存到本地')
    }
    
    // 触发自定义事件，通知背景组件更新
    window.dispatchEvent(new CustomEvent('background-settings-updated'))
    
    // 通知父组件设置已更新
    emit('settings-updated')
    
    // 关闭抽屉
    visible.value = false
  } catch (error) {
    console.error('保存背景设置失败', error)
    ElMessage.error('保存背景设置失败，请重试')
  }
}

// 重置为默认设置
const resetSettings = () => {
  backgroundType.value = 'image'
  backgroundColor.value = 'rgba(107, 70, 193, 0.8)'
  gradientType.value = 'linear'
  gradientDirection.value = 'to bottom right'
  gradientColorStart.value = 'rgba(107, 70, 193, 0.8)'
  gradientColorEnd.value = 'rgba(72, 41, 178, 0.8)'
  backgroundImage.value = '/backgrounds/ganyu.png'
  opacity.value = 0.9
  radialShape.value = 'circle'
  radialPosition.value = 'center'
}

// 处理文件上传
const handleFileChange = (file) => {
  if (!file) return
  
  const isImage = file.raw.type.startsWith('image/')
  if (!isImage) {
    ElMessage.error('只能上传图片文件')
    return
  }
  
  const reader = new FileReader()
  reader.onload = (e) => {
    backgroundImage.value = e.target.result
  }
  reader.readAsDataURL(file.raw)
}

// 测试本地存储
const testLocalStorage = () => {
  try {
    // 测试写入
    localStorage.setItem('test_key', 'test_value')
    console.log('localStorage写入测试成功')
    
    // 测试读取
    const testValue = localStorage.getItem('test_key')
    console.log('localStorage读取测试:', testValue)
    
    // 测试删除
    localStorage.removeItem('test_key')
    console.log('localStorage删除测试成功')
    
    // 测试背景设置
    const savedSettings = localStorage.getItem('background_settings')
    console.log('当前背景设置:', savedSettings ? JSON.parse(savedSettings) : '无')
    
    ElMessage.success('本地存储测试成功')
  } catch (error) {
    console.error('本地存储测试失败:', error)
    ElMessage.error('本地存储测试失败: ' + error.message)
  }
}
</script>

<style scoped>
.background-settings-content {
  padding: 16px;
}

.setting-group {
  margin-bottom: 20px;
}

.setting-label {
  font-size: 14px;
  font-weight: 500;
  margin-bottom: 8px;
  color: var(--el-text-color-primary);
}

.setting-actions {
  display: flex;
  justify-content: space-between;
  margin-top: 24px;
}

.mt-2 {
  margin-top: 8px;
}

.preset-images {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 8px;
  margin-top: 8px;
}

.preset-image {
  width: 100%;
  height: 60px;
  border-radius: 4px;
  background-size: cover;
  background-position: center;
  cursor: pointer;
  border: 2px solid transparent;
  transition: all 0.3s ease;
}

.preset-image:hover {
  transform: scale(1.05);
  border-color: var(--el-color-primary);
}

.debug-panel {
  background: rgba(0, 0, 0, 0.1);
  border-radius: 8px;
  padding: 12px;
  margin-bottom: 20px;
  font-size: 12px;
}

.debug-title {
  font-weight: bold;
  margin-bottom: 8px;
  color: #f59e0b;
}

.debug-button {
  background: rgba(107, 70, 193, 0.8);
  border: none;
  color: white;
  padding: 5px 10px;
  border-radius: 4px;
  font-size: 12px;
  cursor: pointer;
  margin-top: 8px;
}

.debug-button:hover {
  background: rgba(107, 70, 193, 1);
}
</style> 